package com.zlyx.easy.redis.utils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.zlyx.easy.core.jackson.JSONObject;
import com.zlyx.easy.core.utils.StringUtils;

/**
 * <p>
 * redis缓存
 * </p>
 *
 * @author 赵光
 * @version v1.0
 */
@Component
public class RedisCache {

	@Autowired
	public StringRedisTemplate stringRedisTemplate;

	/**
	 * 移除key
	 *
	 * @param key
	 * @throws IOException
	 */
	public void delete(String key) {
		stringRedisTemplate.delete(key);
	}

	/**
	 * 加缓存
	 *
	 * @param key
	 * @param value
	 * @throws IOException
	 */
	public void set(String key, String value) throws IOException {
		stringRedisTemplate.opsForValue().set(key, value, 10, TimeUnit.MINUTES);
	}

	/**
	 * 加缓存
	 *
	 * @param key
	 * @param value
	 * @param timeout
	 * @param unit
	 * @throws IOException
	 */
	public void set(String key, Object value, long timeout, TimeUnit unit) throws IOException {
		stringRedisTemplate.opsForValue().set(key, JSONObject.toString(value), timeout, unit);
	}

	/**
	 * 取缓存
	 *
	 * @param key
	 * @param cls
	 * @param <T>
	 * @return
	 * @throws IOException
	 */
	public <T> T get(String key, Class<T> cls) throws IOException {
		String value = getString(key);
		return StringUtils.isBlank(value) ? null : JSONObject.parseObject(value, cls);
	}

	/**
	 * 取缓存
	 *
	 * @param key
	 * @return
	 * @throws IOException
	 */
	public String getString(String key) throws IOException {
		return stringRedisTemplate.opsForValue().get(key);
	}
}
